#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
向量搜索使用示例
演示如何使用新的向量搜索功能
"""

from vector_tree_query_tool import VectorTreeQueryTool
import requests
import json

def example_direct_search():
    """直接使用查询工具的示例"""
    print("🔍 直接查询工具示例")
    print("=" * 50)
    
    # 创建查询工具
    query_tool = VectorTreeQueryTool()
    
    if not query_tool.neo4j_driver or not query_tool.milvus_collection:
        print("❌ 数据库连接失败")
        return
    
    try:
        # 示例查询
        queries = [
            "TD504的扩增循环数是怎么样的？",
            "PK511温度设置问题",
            "PCR反应失败怎么办",
            "投入量应该是多少"
        ]
        
        for query in queries:
            print(f"\n📝 查询: {query}")
            print("-" * 40)
            
            # 执行向量搜索
            results = query_tool.search_tree_paths_with_vector(query, limit=3)
            
            # 显示结果
            query_tool.display_results(results)
    
    finally:
        query_tool.close()

def example_api_usage():
    """API使用示例"""
    print("\n🌐 API使用示例")
    print("=" * 50)
    
    # API基础URL（假设API在8001端口运行）
    base_url = "http://localhost:8001"
    
    # 测试API是否可用
    try:
        response = requests.get(f"{base_url}/health", timeout=5)
        if response.status_code == 200:
            print("✅ API服务可用")
        else:
            print("❌ API服务不可用")
            return
    except requests.exceptions.RequestException:
        print("❌ 无法连接到API服务，请确保API服务正在运行")
        print("   启动命令: python start_vector_api.py")
        return
    
    # 示例查询
    queries = [
        {
            "query": "TD504扩增循环数",
            "limit": 3
        },
        {
            "query": "温度设置问题",
            "limit": 5
        }
    ]
    
    for query_data in queries:
        print(f"\n📝 API查询: {query_data['query']}")
        print("-" * 40)
        
        try:
            # POST请求
            response = requests.post(
                f"{base_url}/search",
                json=query_data,
                timeout=30
            )
            
            if response.status_code == 200:
                result = response.json()
                print(f"✅ 查询成功")
                print(f"   结果类型: {result['result_type']}")
                print(f"   结果数量: {result['total_count']}")
                print(f"   消息: {result['message']}")
                
                # 显示部分结果
                if result['result_type'] == 'nodes' and result['nodes']:
                    print("   前3个节点:")
                    for i, node in enumerate(result['nodes'][:3], 1):
                        print(f"     {i}. {node['content'][:50]}...")
                        print(f"        相关性: {node['relevance_score']:.3f}")
                        if node.get('vector_similarity'):
                            print(f"        向量相似度: {node['vector_similarity']:.3f}")
                
                elif result['result_type'] == 'chains' and result['chains']:
                    print("   决策链路:")
                    for i, chain in enumerate(result['chains'][:2], 1):
                        print(f"     {i}. 产品: {chain['product_code']}")
                        print(f"        链路长度: {len(chain['chain'])}")
            else:
                print(f"❌ 查询失败: {response.status_code}")
                print(f"   错误: {response.text}")
                
        except requests.exceptions.RequestException as e:
            print(f"❌ 请求失败: {e}")

def example_node_search():
    """节点搜索示例"""
    print("\n🌳 节点搜索示例")
    print("=" * 50)
    
    query_tool = VectorTreeQueryTool()
    
    if not query_tool.neo4j_driver:
        print("❌ Neo4j连接失败")
        return
    
    try:
        # 节点搜索示例
        node_searches = [
            {"node_name": "扩增循环数", "product_code": None},
            {"node_name": "温度设置", "product_code": "TD504"},
            {"node_name": "投入量", "product_code": None}
        ]
        
        for search in node_searches:
            node_name = search["node_name"]
            product_code = search["product_code"]
            
            print(f"\n📝 节点搜索: {node_name}")
            if product_code:
                print(f"   限定产品: {product_code}")
            print("-" * 40)
            
            results = query_tool.search_by_node_name(node_name, product_code)
            
            if results:
                print(f"✅ 找到 {len(results)} 个结果")
                
                # 显示结果类型
                if 'chain' in results[0]:
                    print("   结果类型: 决策链路")
                    for i, result in enumerate(results[:2], 1):
                        print(f"     {i}. 产品: {result['product_code']}")
                        print(f"        链路长度: {len(result['chain'])}")
                else:
                    print("   结果类型: 子节点列表")
                    for i, result in enumerate(results[:3], 1):
                        print(f"     {i}. {result['content'][:50]}...")
                        print(f"        类型: {result['node_type']}")
            else:
                print("❌ 未找到结果")
    
    finally:
        query_tool.close()

def example_comparison():
    """新旧版本对比示例"""
    print("\n⚖️  新旧版本对比示例")
    print("=" * 50)
    
    # 测试查询
    test_query = "TD504扩增循环数"
    
    print(f"📝 测试查询: {test_query}")
    print("-" * 40)
    
    # 新版本（向量搜索）
    print("🆕 新版本 (向量搜索):")
    try:
        vector_tool = VectorTreeQueryTool()
        if vector_tool.neo4j_driver and vector_tool.milvus_collection:
            results = vector_tool.search_tree_paths_with_vector(test_query, limit=3)
            print(f"   找到 {len(results)} 个结果")
            if results and 'relevance_score' in results[0]:
                avg_score = sum(r.get('relevance_score', 0) for r in results) / len(results)
                print(f"   平均相关性: {avg_score:.3f}")
        else:
            print("   ❌ 连接失败")
        vector_tool.close()
    except Exception as e:
        print(f"   ❌ 错误: {e}")
    
    # 旧版本（关键词搜索）
    print("\n🔄 旧版本 (关键词搜索):")
    try:
        from tree_query_tool import TreeQueryTool
        keyword_tool = TreeQueryTool()
        if keyword_tool.driver:
            results = keyword_tool.search_tree_paths(test_query, limit=3)
            print(f"   找到 {len(results)} 个结果")
            if results and 'relevance_score' in results[0]:
                avg_score = sum(r.get('relevance_score', 0) for r in results) / len(results)
                print(f"   平均相关性: {avg_score:.3f}")
        else:
            print("   ❌ 连接失败")
        keyword_tool.close()
    except Exception as e:
        print(f"   ❌ 错误: {e}")

def main():
    """主函数"""
    print("🎯 向量搜索使用示例")
    print("=" * 60)
    
    examples = [
        ("直接查询工具", example_direct_search),
        ("API使用", example_api_usage),
        ("节点搜索", example_node_search),
        ("新旧版本对比", example_comparison)
    ]
    
    for name, func in examples:
        try:
            func()
        except KeyboardInterrupt:
            print("\n👋 用户中断")
            break
        except Exception as e:
            print(f"\n❌ {name} 示例执行失败: {e}")
        
        # 询问是否继续
        if name != examples[-1][0]:  # 不是最后一个
            try:
                input(f"\n按回车键继续下一个示例 ({examples[examples.index((name, func)) + 1][0]})...")
            except KeyboardInterrupt:
                print("\n👋 用户中断")
                break
    
    print("\n🎉 示例演示完成！")

if __name__ == "__main__":
    main()
